package com.zhoust.fastdome.aspect;

import com.alibaba.fastjson.JSONObject;
import com.zhoust.fastdome.business.service.CommonLogService;
import com.zhoust.fastdome.common.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


/**
 * @author zhoust
 * @Date 2021/9/17 22:49
 * @Desc 日志记录切面
 */
@Slf4j
@Aspect
@Component
public class LogAspect {
    @Value("${fast.dome.logType}")
    private String logType;

    private final CommonLogService commonLogService;
    final HttpServletRequest request;


    public LogAspect(CommonLogService commonLogService,HttpServletRequest request) {
        this.commonLogService = commonLogService;
        this.request = request;
    }

    /**
     * 定义切入点
     */
    @Pointcut("@annotation(com.zhoust.fastdome.annnotation.LogAutoRecord)")
    public void getPointCutByAnnotation(){
    }

    @Around("getPointCutByAnnotation()")
    public Object saveLog(ProceedingJoinPoint joinPoint) throws Throwable {
        if(!CommonConstant.aopAnnotation.equals(logType)){
            return joinPoint.proceed();
        }
        log.info("=================基于注解记录日志==========================");


        Object result = "";
        // 执行目标 获取返回值
        try {
            result = joinPoint.proceed();
            commonLogService.saveLog(JSONObject.toJSONString(result),joinPoint);
        } catch (Throwable throwable) {
            log.error("执行方法失败,没有记录返回报文，记录报错信息,异常信息：{}",throwable);
            // 手动抛出异常，便于统一处理拦截
            throw throwable;
        }
        return result;
    }

}
